import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_comment.dart';
import 'package:ceramics/model/ab_like.dart';
import 'package:ceramics/model/ab_oauth.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/main/home/ab_user_works_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_report.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:ceramics/widgets/ab_image.dart';
import 'package:ceramics/widgets/ab_voice_record_overlay.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:get/get.dart';
import 'package:google_translate/google_translate.dart';
import 'package:path_provider/path_provider.dart';

class ABHomeDetailController extends GetxController {
  late final ABWorks works = Get.arguments as ABWorks;
  var comments = <ABComment>[].obs;

  late final images = works.images.split(",").map((e) => e.trim()).toList();
  var translateText = "".obs;
  var showTranslate = false.obs;
  var textController = TextEditingController();
  var playController = PlayerController();
  Rx<int> currentPlayingId = (-1).obs;
  late var playerState = playController.playerState.obs;

  Worker? debounceWorker;
  var dLike = true.obs;
  ABWorks? handleModel;

  @override
  void onInit() {
    super.onInit();
    queryComments();
    playController.onPlayerStateChanged.listen((event) {
      playerState.value = event;
    });
    debounceWorker = debounce(dLike, (callback) async {
      var model = handleModel!;
      var likeId = 'works_${model.id}';
      var isLike = model.isLiked.value;
      if (isLike) {
        if (ABSingleton.likes.any((element) => element.likeId == likeId)) {
          return;
        }
        await ABLike.insertLike(likeId);
        ABSingleton.likes.value = await ABLike.queryAllLikes();
        await model.save();
      } else {
        await ABLike.deleteLike(likeId);
        ABSingleton.likes.value = await ABLike.queryAllLikes();
        await model.save();
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    queryComments();
  }

  @override
  void onClose() {
    playController.dispose();
    textController.dispose();
    super.onClose();
  }

  @override
  void dispose() {
    debounceWorker?.dispose();
    playController.dispose();
    textController.dispose();
    super.dispose();
  }

  void toggleFollow() async {
    if (ABSingleton.didFollow(works.userId)) {
      await api.unfollow(works.userId);
      ABSingleton.follows
          .removeWhere((element) => element.userId == works.userId);
    } else {
      await api.follow(works.userId);
      await ABSingleton.updateFollows();
    }
    Get.find<ABHomeDetailController>().update();
  }

  void showMoreMenu() {

  }

  void translate() async {
    if (translateText.value.isEmpty && !showTranslate.value) {
      loading();
      translateText.value = await works.detail.translate();
      dismissLoading();
    }
    showTranslate.value = !showTranslate.value;
  }

  Future<void> queryComments() async {
    var c = await ABComment.queryForWorks(works.id);
    comments.value = c;
  }
}

class ABHomeDetailPage extends GetView<ABHomeDetailController> {
  final String id;
  @override
  final ABHomeDetailController controller;

  ABHomeDetailPage({super.key, required this.id})
      : controller = Get.put(ABHomeDetailController(), tag: id);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        foregroundColor: Colors.white,
        actions: [_buildTitle(), 20.toHorizontalBox],
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Stack(
          children: [
            ListView(
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              children: [_buildTopBanner(), _buildDetail(), _buildComments()],
            ),
            _buildInput()
          ],
        ).minHeight(Get.height),
      ),
    );
  }

  Widget _buildTopBanner() {
    return Stack(
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 400,
              child: Swiper(
                itemCount: controller.images.length,
                itemBuilder: (context, index) {
                  return ABImage(url: controller.images[index],
                      fit: BoxFit.cover);
                },
                pagination: SwiperPagination(
                    margin: const EdgeInsets.only(bottom: 20),
                    builder: DotSwiperPaginationBuilder(
                        activeColor: ABStyles.darkPink,
                        color: ABStyles.lightPink.withOpacity(0.3))),
                controller: SwiperController(),
              ),
            ),
            Transform(
              transform: Matrix4.translationValues(0, -10, 0),
              child: Container(
                height: 10,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10),
                      topRight: Radius.circular(10)),
                ),
              ),
            ).paddingOnly(bottom: 30),
          ],
        ),
        Obx(() {
          return Positioned(
            bottom: 0,
            right: 10,
            child: Image.asset(
                controller.works.isLiked.value
                    ? 'images/ceramics_9.webp'
                    : 'images/ceramics_44.webp',
                width: 80,
                fit: BoxFit.cover).onTap(_toggleLike),
          );
        })
      ],
    );
  }

  Widget _buildTitle() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(30),
        color: Colors.black87.withOpacity(0.5),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          10.toHorizontalBox,
          Row(
            mainAxisSize: MainAxisSize.max,
            children: [
              ABCircleAvatar(
                  url: controller.works.avatarOss?.thumbUrl, size: 40),
              5.toHorizontalBox,
              Text(controller.works.nickname,
                  style: const TextStyle(color: Colors.white, fontSize: 17),softWrap: false,overflow: TextOverflow.fade).size(width: controller.works.userId != ABSingleton.user?.userId ? 70 : 80),
              40.toHorizontalBox,
            ],
          ).onTap(() =>
              Get.to(() =>
                  ABUserWorksPage(user: ABUser()
                    ..nickname = controller.works.nickname
                    ..userId = controller.works.userId
                    ..avatar = controller.works.avatar
                  ), arguments: controller.works.userId)),
          Visibility(
              visible: controller.works.userId != ABSingleton.user?.userId,
              child:Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                Obx(() {
                  return ABSingleton.didFollow(controller.works.userId)
                      ? TextButton(
                      onPressed: controller.toggleFollow,
                      child:
                      const Text("Unfollow", style: ABStyles.tsWhite17Bold))
                      : ABElevateButton(
                      onPressed: controller.toggleFollow,
                      child:
                      const Text('＋ Follow', style: ABStyles.tsWhite17Bold));
                }).maxHeight(35),
                5.toHorizontalBox,
                Image.asset('images/more_v.webp',width: 30,height: 30).onTap(()=>showMoreReport(controller.works.userId)),
                10.toHorizontalBox
              ])
          )
        ],
      ),
    );
  }

  Widget _buildDetail() {
    return Container(
      width: double.infinity,
      alignment: Alignment.topLeft,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(controller.works.title, style: ABStyles.tsDarkBlack19Bold),
          10.toVerticalBox,
          Obx(() {
            return Text(
                controller.showTranslate.value
                    ? controller.translateText.value
                    : controller.works.detail,
                style: ABStyles.tsNormalBlack15);
          }).maxWidth(Get.width - 24),
          Row(
            children: [
              const Spacer(),
              TextButton(
                  onPressed: controller.translate,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Image.asset('images/ceramics_68.webp', width: 20),
                      const SizedBox(width: 5),
                      const Text("Translate", style: ABStyles.tsLightBlack15)
                    ],
                  ))
            ],
          ),
          Obx(() {
            return Text('${"Comment".tr}(${controller.comments.length})',
                style: ABStyles.tsDarkBlack19Bold);
          }),
        ],
      ),
    );
  }

  Widget _buildInput() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 34),
        decoration: const BoxDecoration(color: Colors.white, boxShadow: [
          BoxShadow(
            color: Colors.black12,
            offset: Offset(0, -2),
            blurRadius: 5,
          )
        ]),
        child: Row(
          children: [
            ABElevateButton(
                style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.all(0),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(25))),
                onPressed: _showVoiceRecord,
                child: const Icon(Icons.keyboard_voice_outlined))
                .size(width: 40, height: 40),
            10.toHorizontalBox,
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                border: Border.all(color: ABStyles.lightBlack),
              ),
              child: Row(
                children: [
                  CupertinoTextField.borderless(
                    controller: controller.textController,
                    prefix: 10.toHorizontalBox,
                    placeholder: "Enter your ideas...".tr,
                    placeholderStyle: ABStyles.tsLightBlack15,
                    style: ABStyles.tsDarkBlack15,
                    // 最多3行，动态变化
                    maxLines: 4,
                    minLines: 1,
                  ).expand(),
                  10.toHorizontalBox,
                  Image.asset('images/ceramics_4.webp', width: 30)
                      .onTap(_sendComment),
                  5.toHorizontalBox
                ],
              ).minHeight(40),
            ).expand()
          ],
        ),
      ),
    );
  }

  void _showVoiceRecord() async {
    var path = await showVoiceRecordOverlay();
    if (path != null) {
      loading();
      var user = ABSingleton.user!;
      var comment = ABComment(
          type: 1,
          value: path,
          nickname: user.nickname,
          avatar: user.avatar,
          worksId: controller.works.id,
          userId: user.userId);
      await comment.save();
      await controller.queryComments();
      await Future.delayed(const Duration(seconds: 1));
      dismissLoading();
    }
  }

  _sendComment() async {
    loading();
    var user = ABSingleton.user!;
    var comment = ABComment(
        type: 0,
        value: controller.textController.text,
        nickname: user.nickname,
        avatar: user.avatar,
        worksId: controller.works.id,
        userId: user.userId);
    await comment.save();
    controller.textController.clear();
    await controller.queryComments();
    await Future.delayed(const Duration(seconds: 1));
    FocusScope.of(Get.context!).unfocus();
    dismissLoading();
  }

  Widget _buildComments() {
    return Obx(() {
      return ListView.separated(
        physics: const NeverScrollableScrollPhysics(),
        padding:
        const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 120),
        shrinkWrap: true,
        itemCount: controller.comments.length,
        separatorBuilder: (context, index) {
          return 10.toVerticalBox;
        },
        itemBuilder: (context, index) {
          var comment = controller.comments[index];
          return ListTile(
            tileColor: ABStyles.lightPink.withOpacity(0.1),
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            leading: ABCircleAvatar(url: comment.avatar, size: 40),
            contentPadding: const EdgeInsets.symmetric(horizontal: 10),
            title: Text(comment.nickname),
            subtitle: comment.type == 0
                ? Text(comment.value).paddingOnly(top: 10)
                : _buildVoicePlayButton(comment),
          );
        },
      );
    });
  }

  Widget _buildVoicePlayButton(ABComment comment) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        ABElevateButton(
          onPressed: () => _play(comment),
          child: Row(
            children: [
              const Icon(Icons.play_arrow),
              Obx(() {
                return controller.currentPlayingId.value != comment.id ||
                    controller.playerState.value != PlayerState.playing ?
                Image.asset('images/ceramics_40.webp', width: 100,
                    height: 25,
                    color: Colors.white)
                    :
                AudioFileWaveforms(
                    size: const Size(100, 25),
                    playerController: controller.playController);
              })
            ],
          ),
        ),
        const Spacer()
      ],
    ).paddingOnly(top: 10);
  }

  _play(ABComment comment) async {
    var docDir = await getApplicationDocumentsDirectory();
    var path = "${docDir.path}/${comment.value}";
    await controller.playController.preparePlayer(path: path);
    await controller.playController.startPlayer(finishMode: FinishMode.stop);
    controller.currentPlayingId.value = comment.id ?? -1;
  }

  _toggleLike() async {
    controller.works.isLiked.value = !controller.works.isLiked.value;
    controller.works.likes = controller.works.isLiked.value
        ? controller.works.likes + 1
        : controller.works.likes - 1;
    controller.dLike.value = !controller.dLike.value;
    controller.handleModel = controller.works;
  }
}
